<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit='formSubmit'
	 :showHistoryBtn="true">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-sub :title="ms_title" :subTitle="ms_subtitle">
			<view slot="extra">{{workList.length?'点击项目可进行编辑':''}}</view>
			<uni-list>
				<view v-for="(item, index) in workList" :key="index">
					<uni-list-item :avatar="index + 1" :showArrow="true" @click="openWork(index)" :showClear="true" @iconClear="delSub(index)">
						<view>{{item.itemName + "("+item.orderNum+")"}}</view>
						<view class="text-gray text-sm padding-bottom-xs padding-top-xs">{{item.workStandard}}</view>
						<view class="text-gray text-sm">{{dateFunc(item)}}</view>
					</uni-list-item>
				</view>
			</uni-list>
			<view v-if="subConfigData.length" class="tui-flex align-center justify-center padding-top">
				<text class="lg text-green cuIcon-add" @click="openWork()">{{"增加"+ms_title}}</text>
			</view>
		</om-sub>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
	import {
		getUrl
	} from '@/static/js/common.js';
	import {
		buildFormData,
		getFormFields,
		formValidation,
		tranferToEditors,
		changeEditor,
		configSelectData
	} from '@/static/js/formUtil.js';
	import { mapState, mapActions } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	export default {
		provide() {
			return {
				formPage: this
			};
		},
		data() {
			return buildFormData({
				menuName: '',
				id: '',
				busCode: 'PER0301',
				formdata: {},
				mainConfigData: [],
				subConfigData: [],
				initValue: {
					objStr: "",
					busCode: 'PER0301',
				},
				workitemCacheKey: "pm-work-report-workitem-cache",
				workCacheKey: "pm-work-report-work-cache",
				workConfigDataCacheKey: "pm-work-report-work-configdata-cache",
				workList: [],
				ms_title: "明细",
				ms_subtitle: "",
				initItemName: ""
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		methods: {
			...mapActions(useLoginUserStore, [
				'setRecentWork'
			]),
			formSubmit() {
				let _that = this
				if (!this.workList.length) {
					this.om.toast("请配置" + this.ms_title)
					return
				}
				for (var i = 0; i < this.workList.length; i++) {
					if (!this.workList[i].fileList || !this.workList[i].fileList.length) {
						delete this.workList[i].fileList
					}
					var checkRes = formValidation(this.subConfigData, this.workList[i])
					if (checkRes) {
						this.om.toast("第" + (i + 1) + "条" + this.ms_title + "：" + checkRes)
						return
					}
				}
				this.formdata.objStr = JSON.stringify(this.workList)
				this.om.formSave('tkeyWorkReport/addTkeyWorkReport', this.formdata, this, function(id) {
					if (_that.initItemName && _that.workList.filter(e => _that.initItemName === e.itemName).length) {
						_that.setRecentWork(true)
					}
					_that.om.getFormInfo(id, _that.busCode, true);
				})
			},
			dateFunc(item) {
				var s = ''
				if (item.planEndDate) {
					s += '计划' + item.planEndDate + '完成'
				}
				if (s) {
					s += ','
				}
				if (item.actualEndDate) {
					s += '实际' + item.actualEndDate + '完成'
				} else {
					s += '实际完成时间未填写'
				}
				return s
			},
			openWork(index) {
				uni.setStorage({
					key: this.workConfigDataCacheKey,
					data: this.subConfigData
				})
				uni.setStorage({
					key: this.workCacheKey,
					data: this.workList
				})
				var param = {
					configDataCacheKey: this.workConfigDataCacheKey,
					cachename: this.workCacheKey,
					index: index,
					busCode:this.busCode
				}
				var url = getUrl("data-info", param)
				uni.navigateTo({
					url: url
				});
			},
			initLoad(options) {
				let _that = this
				if (!this.busCode) {
					return
				}
				var itemid = options.itemid
				var fileId = options.fileId

				var pro1 = _that.om.request('formFieldConfig/showPage', {
					code: this.busCode
				})
				var pro2 = _that.om.request('tkeyWorkReport/getDataList')
				var ajaxArr = [pro1, pro2]
				if (fileId) {
					var pro3 = _that.om.request("tkeyWorkReport/getInfo", {
							id: fileId
						},
						"post")
					ajaxArr.push(pro3)
				}
				if (itemid) {
					if (this._.toInteger(itemid)) {
						var pro4 = _that.om.request("tkeyWorkList/getWorkItem", {
							id: itemid
						})
						ajaxArr.push(pro4)
					}
				}
				Promise.all(ajaxArr).then(
					(res) => {
						if (res[0].succeed) {
							let data = res[0].value
							var mainData = [{
								key: 'topinfo',
								editors: tranferToEditors(data.top)
							}];
							changeEditor(mainData[0].editors, 'zuserId', 'defaultValue', _that.userId);
							changeEditor(mainData[0].editors, 'zuserId', 'defaultName', _that.userName);
							if (data.bodyTitle.length > 0) {
								_that.ms_title = data.bodyTitle[0].itemName
								for (var i = 0; i < data.bodyTitle.length; i++) {
									var datas = data["body" + i];
									_that.subConfigData.push({
										title: data.bodyTitle[i].itemName,
										key: data.bodyTitle[i].fieldId,
										issub: true,
										editors: tranferToEditors(datas)
									})
								}
							}
							//赋值
							_that.$refs.autoform.configData = mainData;

							if (fileId) {
								var fieldArr = getFormFields(mainData)
								fieldArr.push("id")
								for (var item in res[2].value.tkeyWorkReport) {
									if (fieldArr.includes(item)) {
										_that.$refs.autoform.$set(_that.$refs.autoform.formdata, item, res[2].value.tkeyWorkReport[item])
										_that.$set(_that.formdata, item, res[2].value.tkeyWorkReport[item])
									}
								}
							}
							//默认加载数据
							if (itemid) {
								var it = null
								if (fileId) {
									it = res[3].value
									if (it) {
										var obj = {
											orderNum: it.orderNumStr,
											itemName: it.workName,
											workStandard: it.workOutput,
											deliveryName: it.deliveryName,
											keyItem: it.keyItem ? '√' : '',
											deliveryName: it.deliveryName,
											planEndDate: it.planEnd,
											evaluateUserId: it.evaluateUserId,
											evaluateUserName: it.evaluateUserName,
											listId:it.listId
										}
										_that.initItemName = it.workName
										_that.workList = [obj]
									}
								} else {
									it = res[2].value
									if (it) {
										var obj = {
											orderNum: it.orderNumStr,
											itemName: it.workName,
											workStandard: it.workOutput,
											deliveryName: it.deliveryName,
											keyItem: it.keyItem ? '√' : '',
											deliveryName: it.deliveryName,
											planEndDate: it.planEnd,
											evaluateUserId: it.evaluateUserId,
											evaluateUserName: it.evaluateUserName,
											listId: it.id
										}
										_that.initItemName = it.workName
										_that.workList = [obj]
									}
								}
								
							} else {
								_that.$nextTick(function() {
									if (fileId) {
										_that.workList = res[2].value.tkeyWorkReport_data
									} else {
										_that.workList = res[1].value
									}
								})
							}
						} else {
							_that.om.toast(res[0].msg)
						}
					}
				).catch(
					(err) => {
						console.log(err)
					}
				)
			},
			delSub(index) {
				if (index != null) {
					this.workList.splice(index, 1)
				}
			}
		},
		onLoad(options) {
			let _that = this;
			_that.menuName = options.title || '工作报告单';
			uni.setNavigationBarTitle({
				title: _that.menuName
			});
			_that.busCode = options.code;
			_that.formdata.userId = this.userId
			uni.removeStorage({
				key: _that.workCacheKey
			});
			_that.initLoad(options);

			//#ifdef APP-PLUS
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
			//#endif
		},
		onShow() {
			let _that = this
			uni.getStorage({
				key: _that.workCacheKey,
				success: function(res) {
					_that.workList = res.data;
					uni.removeStorage({
						key: _that.workCacheKey
					})
				}
			});
		}
	}
</script>
<style>
</style>
